﻿using RabbitMQ.Client;
using SHRIS.MIS.Common.Util;
using System;
using System.Collections.Generic;
using System.Text;

namespace SHRIS.MIS.Service.RabbitService
{
    public class DeviceAlarmPublisherService
    {
        private readonly IConnection _rabbitConnection;
        private readonly IModel _channel;
        private readonly string _strMQChannel;
        private readonly string _strMQQueue;
        private readonly string _strMQRoute;

        public DeviceAlarmPublisherService(IConnection rabbitConnection, string strMQChannel, string strMQQueue, string strMQRoute)
        {
            _strMQChannel = strMQChannel;
            _strMQQueue = strMQQueue;
            _strMQRoute = strMQRoute;
            _rabbitConnection = rabbitConnection;
            _channel = _rabbitConnection.CreateModel();

            _channel.ExchangeDeclare(_strMQChannel, "topic");


            _channel.QueueDeclare(_strMQQueue, true, false, false);
            _channel.QueueBind(_strMQQueue, _strMQChannel, _strMQRoute);

        }

        public void PublishMsg(string message)
        {

            _channel.ConfirmSelect();


            var properties = _channel.CreateBasicProperties();
            properties.Persistent = true;

            properties.MessageId = Guid.NewGuid().ToString("N");
            properties.Timestamp = new AmqpTimestamp(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());

            properties.Headers = new Dictionary<string, object>
                        {
                            { "key", properties.MessageId }
                        };

            var body = Encoding.UTF8.GetBytes(message);

            _channel.BasicPublish(_strMQChannel, _strMQRoute, properties, body);

            var isOk = _channel.WaitForConfirms();
            if (!isOk)
            {
                LogHelper.Error("The message is not reached to the server! " + message);
            }
        }
    }
}
